package com.ximu.sharenet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.util.Log;

/**
 * shell 脚本管理
 */
public class ShellManage{
	
	//shell
	static final String SET_NET_USB 	="su busybox route del default\nsu busybox route add default gw 192.168.42.8\nsu setprop net.dns1 8.8.8.8";		//设置USB上网
	static final String SET_NET_WIFI 	="su busybox route del default\nsu busybox route add default gw 192.168.43.8\nsu setprop net.dns1 8.8.8.8";		//设置WIFI上网信息
	static final String UTIL_PING		="ping -c 1 -w 5 ";//ping
}
//回调类
abstract class  CallBack{
	abstract void run(String out,String error,String exc);
}

//新线程执行脚本
class ExeCMD extends Thread{
	
	private CallBack  callBack;
	private String cmd;
	
	public ExeCMD(String cmd,CallBack callBack) {
		this.cmd = cmd;
		this.callBack = callBack;
	}
	
	public void exe(){
		Process pro = null;
		String out ="",error="",exc ="",line;
		try {
			//执行多条语句
			String[] cmds = cmd.split("\n");
			for(String one:cmds){
				Log.i("my", "命令:"+one);
				String oneOut="",oneError = "";
				pro = Runtime.getRuntime().exec(one);
				//标准输去信息
				BufferedReader readIn = new BufferedReader(new InputStreamReader(pro.getInputStream()));
				while((line = readIn.readLine()) != null){
					out = out +"\n"+line;
					oneOut = oneOut + "\n" + line;
				}
				//错误输出信息
				BufferedReader readErr = new BufferedReader(new InputStreamReader(pro.getErrorStream()));
				while((line = readErr.readLine()) != null){
					error = error +"\n"+line;
					oneError = oneError  +"\n"+line;
				}
				Log.i("my","输出:"+oneOut+oneError);
			}
			
		} catch (IOException e) {
			exc = e.getMessage();
		}finally{
			if(pro != null){
				pro.destroy();
			}
			callBack.run(out,error,exc);
		}		
	}

	@Override
	public void run() {
		exe();
	}
}
